package ihistoryApp.config;

import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class RedisClient {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public boolean set(String key, String value, Long expire) {
        if (expire == null) {
            stringRedisTemplate.opsForValue().set(key, value);
            return true;
        }
        stringRedisTemplate.opsForValue().set(key, value, Duration.ofMillis(expire));
        log.info("redis.get:{}", stringRedisTemplate.getExpire(key));
        return true;
    }

    public String get(String key) {
        log.info("redis key:{}", key);
        return stringRedisTemplate.opsForValue().get(key);
    }

    public boolean isExist(String key) {
        if (StringUtil.isNullOrEmpty(key)) {
            return false;
        }
        return Boolean.TRUE.equals(stringRedisTemplate.hasKey(key));
    }

    public long inc(String key) {
        if (isExist(key)) {
            return stringRedisTemplate.opsForValue().increment(key);
        } else {
            set(key, "1", null);
            return 1;
        }
    }

    public long inc(String key, long expire) {
        if (isExist(key)) {
            stringRedisTemplate.expire(key, expire, TimeUnit.MILLISECONDS);
            return stringRedisTemplate.opsForValue().increment(key);
        } else {
            set(key, "1", expire);
            return 1;
        }
    }
    public long dec(String key) {
        if (isExist(key)) {
            return stringRedisTemplate.opsForValue().decrement(key);
        } else {
            throw new RuntimeException("操作失败");
        }
    }

    public void expire(String key) {
        if (isExist(key)) {
            stringRedisTemplate.expire(key, 1L, TimeUnit.MILLISECONDS);
        }
    }

}